package com.yxx.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.yxx.mapper.*;
import com.yxx.medicinecommon.constant.MessageConstant;
import com.yxx.medicinecommon.context.BaseContext;
import com.yxx.medicinecommon.exception.AddressBookBusinessException;
import com.yxx.medicinecommon.exception.OrderBusinessException;
import com.yxx.medicinecommon.exception.ShoppingCartBusinessException;
import com.yxx.medicinecommon.result.PageResult;
import com.yxx.medicinecommon.utils.WeChatPayUtil;
import com.yxx.medicinepojo.dto.*;
import com.yxx.medicinepojo.entity.*;
import com.yxx.medicinepojo.vo.OrderPaymentVO;
import com.yxx.medicinepojo.vo.OrderStatisticsVO;
import com.yxx.medicinepojo.vo.OrderSubmitVO;
import com.yxx.medicinepojo.vo.OrderVO;
import com.yxx.service.OrderService;
import com.yxx.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author yuxiangxun
 * @date 2024/9/16
 * @apiNote
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    private static final Integer TO_BE_CONFIRMED = 2;

    private static final String USER_CANCEL = "用户取消";

    @Autowired
    private WebSocketServer webSocketServer;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private WeChatPayUtil wxChatPayUtil;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private WeChatPayUtil weChatPayUtil;

    @Autowired
    private UserMapper userMapper;

    private AddressBook addressBook;

    private Orders orders;

    /**
     * 订单搜索（分页查询）
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        Page<Orders> orderVOPage  = orderMapper.pageQueryOrders(ordersPageQueryDTO);
        PageResult pageResult = new PageResult();
        pageResult.setTotal(orderVOPage.getTotal());
        //通过订单状态，需要额外返回订单药品信息，将Order转化为OrderVO
        List<OrderVO> orderVOList = getOrderVOList(orderVOPage);
        pageResult.setRecords(orderVOList);

        return pageResult;
    }

    /**
     * 分页查询后对分页记录的更新修改
     * 通过订单状态，需要额外返回订单药品信息，将Order转化为OrderVO
     * @param page
     * @return
     */
    private List<OrderVO> getOrderVOList(Page<Orders> page){
        //需要返回药品信息信息（集合），自定义OrderVO列表
        List<OrderVO> orderVOList = new ArrayList<>();
        //获取分页后的ordersList数据集合
        List<Orders> ordersList = page.getResult();
        if(!CollectionUtils.isEmpty(ordersList)){
            for(Orders order : ordersList){
                log.info("order:{}",order);
                //对象拷贝
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(order,orderVO);
                //获取药品信息   根据订单id获取药品信息字符串
                String orderMedicines = getOrderMedicineStr(order);
                //将订单药品信息封装到orderVO 中，并添加到orderVOList
                orderVO.setOrderMedicines(orderMedicines);
                orderVOList.add(orderVO);
            }
        }
        return orderVOList;
    }

    /**
     * 根据订单id获取药品信息字符串
     * @param order
     * @return
     */
    private String getOrderMedicineStr(Orders order) {
        //查询订单药品详情信息（订单中的药品和数量）
        List<OrderDetail> orderDetailList = orderDetailMapper.geOrderDetailtByOrderId(order.getId());

        //将每一条订单药品信息拼接成为字符串（格式：众生丸50g/瓶*3;）
        List<String> NewOrderDetailList = orderDetailList.stream().map(orderDetail -> {
            String orderMedicineName = orderDetail.getName() + "*" + orderDetail.getName() + ";";
            return orderMedicineName;
        }).collect(Collectors.toList());

        //将该订单对应的所有药品信息拼接在一起
        return String.join("",NewOrderDetailList);
    }

    /**
     * 订单各个状态的数量统计
     * @return
     */
    @Override
    public OrderStatisticsVO orderStatics() {
        //根据状态，分别查询出待接单、待派送、派送中的订单数量
        //查询出待接单的数量（2）
        Integer OrderToBeConfirmed =  orderMapper.countStatus(Orders.TO_BE_CONFIRMED);
        //查询出待派送的数量（3）
        Integer OrderConfirmed = orderMapper.countStatus(Orders.CONFIRMED);
        //查询出派送中的数量（4）
        Integer OrderDeliveryInProgress = orderMapper.countStatus(Orders.DELIVERY_IN_PROGRESS);

        //将查询出来的数据封装到orderStatisticVO中响应数据
        OrderStatisticsVO orderStatisticsVO = OrderStatisticsVO.builder()
                .toBeConfirmed(OrderToBeConfirmed)
                .confirmed(OrderConfirmed)
                .deliveryInProgress(OrderDeliveryInProgress)
                .build();
        return orderStatisticsVO;
    }

    /**
     * 订单接单功能（点击接单修改订单状态）
     * @param ordersConfirmDTO
     */
    @Override
    public void OrderConfirm(OrdersConfirmDTO ordersConfirmDTO) {
        //通过ordersConfirmDTO中获取到当前订单id，将id封装到Order对象中，进行修改状态（动态修改）操作
        Long orderById = ordersConfirmDTO.getId();
        //修改状态为已接单 3
        Integer orderStatus = Orders.CONFIRMED;
        Orders order = new Orders();
        order.setId(orderById);
        order.setStatus(orderStatus);
        orderMapper.update(order);
    }

    /**
     * 订单拒单功能（点击拒单修改订单状态）同时实现支付功能（现在先不做）
     * @param ordersRejectionDTO
     */
    @Override
    public void OrderRejection(OrdersRejectionDTO ordersRejectionDTO) throws Exception {
        //根据订单id查询订单信息
        Long orderById = ordersRejectionDTO.getId();
        Orders order = orderMapper.getOrderById(orderById);

        //只有订单状态为2（待接单）的时候才可以拒单
        //首先判断根据id是否能查询到订单信息，为空抛出自定义异常,显示“订单不存在”
        if(order == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //如果能查询到订单信息，订单状态不为2，也要抛出自定义异常，显示“订单状态错误”
        if(!Orders.TO_BE_CONFIRMED.equals(order.getStatus())){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //支付状态
        Integer payStatus = order.getPayStatus();
        if(Orders.PAID.equals(payStatus)){
            //用户已支付，需要退款  暂时不实现
            //String refund = weChatPayUtil.refund(
            //        order.getNumber(),
            //        order.getNumber(),
            //        new BigDecimal(0.01),
            //        new BigDecimal(0.01)
            //);
        }

        //拒单需要退款，根据订单id订单状态、拒绝原因、操作时间 封装到order对象进行（动态修改）操作
        //获取查询到的数据的id，将修改后的状态，新增的拒绝原因和取消时间封装到updateOrder对象进行动态修改操作
        Long orderId = order.getId();
        Integer orderCancelled =  Orders.CANCELLED;
        String rejectionReason = ordersRejectionDTO.getRejectionReason();
        LocalDateTime CancelNewTime = LocalDateTime.now();
        Orders updateOrder = new Orders();
        updateOrder.setId(orderId);
        updateOrder.setStatus(orderCancelled);
        updateOrder.setRejectionReason(rejectionReason);
        updateOrder.setCancelTime(CancelNewTime);
        orderMapper.update(updateOrder);
    }

    /**
     * 订单取消功能（点击取消修改订单状态） 同时实现支付功能（现在先不做）
     * @param ordersCancelDTO
     */
    @Override
    public void OrderCancel(OrdersCancelDTO ordersCancelDTO) throws Exception{
        //根据传递过来的订单id查询订单
        Long orderById = ordersCancelDTO.getId();
        Orders order = orderMapper.getOrderById(orderById);
        //抛出异常，显示 “订单不存在”
        if(order == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //支付状态
        Integer payStatus = order.getPayStatus();
        if(Orders.PAID.equals(payStatus)){
            //用户已支付，需要退款 暂时先不做
            //String refund = weChatPayUtil.refund(
            //        order.getNumber(),
            //        order.getNumber(),
            //        new BigDecimal(0.01),
            //        new BigDecimal(0.01)
            //);
        }

        //取消需要退款，根据订单id订单状态、取消原因、操作时间 封装到order对象进行（动态修改）操作
        //获取查询到的数据的id，将修改后的状态，新增的取消原因和取消时间封装到updateOrder对象进行动态修改操作
        Orders updateOrder  = new Orders();
        Long updateOrderById = ordersCancelDTO.getId();
        Integer updateOrderByCancelled = Orders.CANCELLED;
        String cancelReason = ordersCancelDTO.getCancelReason();
        LocalDateTime updateOrderByCancelNewTime = LocalDateTime.now();

        updateOrder.setId(updateOrderById);
        updateOrder.setStatus(updateOrderByCancelled);
        updateOrder.setCancelReason(cancelReason);
        updateOrder.setCancelTime(updateOrderByCancelNewTime);

        orderMapper.update(updateOrder);
    }

    /**
     * 订单派送
     * @param id
     */
    @Override
    public void OrderDelivery(Long id) throws Exception{
        //根据id查询订单
        Orders order = orderMapper.getOrderById(id);

        //校验订单是否存在，不存在的话，抛出自定义异常，显示“订单不存在”
        if(order == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //校验订单状态是否为已接单（3）状态，如果状态不为已接单（3）状态的话,抛出自定义异常，显示“订单状态错误”
        log.info("order.getStatus():{}",order.getStatus());
        if(!Orders.CONFIRMED.equals(order.getStatus())){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //更新订单状态，将要更新的订单状态和订单id封装到updateOrder对象，进行动态修改操作
        Orders updateOrder = new Orders();
        //将已接单的状态设置状态为派送中
        Integer OrderDeliveryInProgress = Orders.DELIVERY_IN_PROGRESS;
        //获取订单id
        Long orderId = order.getId();

        updateOrder.setId(orderId);
        updateOrder.setStatus(OrderDeliveryInProgress);

        orderMapper.update(updateOrder);
    }

    /**
     * 完成订单
     * @param id
     */
    @Override
    public void OrderComplete(Long id) throws Exception{
        //根据id查询订单
        Orders order = orderMapper.getOrderById(id);

        //校验订单是否存在，不存在的话，抛出自定义异常，显示“订单不存在”
        if(order == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //校验订单状态是否为派送中（4）状态，如果状态不为派送中（4）状态的话,抛出自定义异常，显示“订单状态错误”
        if(!Orders.DELIVERY_IN_PROGRESS.equals(order.getStatus())){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //更新订单状态，将要更新的订单状态和订单id封装到updateOrder对象，进行动态修改操作
        Orders updateOrder = new Orders();

        //将派送中的状态设置状态为完成
        Integer updateOrderCompleted = Orders.COMPLETED;

        //获取订单id
        Long updateOrderId = order.getId();

        //完成时间
        LocalDateTime updateOrderDeliveryTime = LocalDateTime.now();

        updateOrder.setId(updateOrderId);
        updateOrder.setStatus(updateOrderCompleted);
        updateOrder.setDeliveryTime(updateOrderDeliveryTime);

        orderMapper.update(updateOrder);
    }

    /**
     * 查询订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO orderDetails(Long id) {
        //根据id查询订单信息
        Orders order = orderMapper.getOrderById(id);

        //通过订单信息获取订单id
        Long orderById = order.getId();

        //根据订单id查询订单明细（集合）
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orderById);

        //创建OrderVO对象
        OrderVO orderVO = new OrderVO();

        //对象拷贝
        BeanUtils.copyProperties(order,orderVO);

        //将订单明细（集合） 封装到 OrderVO 对象中
        orderVO.setOrderDetailList(orderDetailList);

        return orderVO;
    }

    /**
     * 用户下单
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    @Transactional
    public OrderSubmitVO userSubmit(OrdersSubmitDTO ordersSubmitDTO) {
        //处理各种业务异常（下单情况下：地址为空、购物车为空）

        //地址为空的情况，抛出地址为空的异常信息
        //通过ordersSubmitDTO中获取到地址id
        Long addressBookById = ordersSubmitDTO.getAddressBookId();

        //根据地址查询地址信息 -》 对象
        AddressBook addressBook = addressBookMapper.getAddressBookById(addressBookById);

        //如果查询出来的地址信息对象为空，抛出地址为空的异常
        if(addressBook == null){
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        //检查用户的收货地址是否超出配送范围（先不做）

        //购物车为空的情况
        //创建shoppingCart对象
        ShoppingCart shoppingCart = new ShoppingCart();

        //获取当前微信登录用户id
        Long wx_user_id = BaseContext.getCurrentId();

        //将当前微信登录用户id封装到shoppingCart对象中
        shoppingCart.setUserId(wx_user_id);

        //根据当前用户id查询购物车信息 -》 对象集合
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.ShowShoppingCartList(shoppingCart);

        //如果购物车信息集合为空，抛出购物车为空的业务异常
        if(CollectionUtils.isEmpty(shoppingCartList)){
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //向订单表插入一条数据
        //创建orders对象
        Orders orders = new Orders();

        //对象拷贝
        BeanUtils.copyProperties(ordersSubmitDTO,orders);

        //将订单时间、详细地址、时间戳作为订单号、待付款状态、未付款状态、电话、当前送货人、当前用户id封装到orders对象中
        orders.setAddress(addressBook.getDetail());
        orders.setOrderTime(LocalDateTime.now());
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        /**
         * 待付款
         */
        orders.setStatus(Orders.PENDING_PAYMENT);
        /**
         * 未付款
         */
        orders.setPayStatus(Orders.UN_PAID);
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setUserId(wx_user_id);

        this.orders = orders;

        //插入数据
        orderMapper.insert(orders);

        //向订单明雄表插入n条数据
        //用List集合封装n条订单数据
        List<OrderDetail> orderDetailList = new ArrayList<>();
        //遍历购物车记录  =》 n条购物车的记录
        for(ShoppingCart cart : shoppingCartList){
            //订单明细
            //创建orderDetail对象
            OrderDetail orderDetail = new OrderDetail();
            //对象拷贝
            BeanUtils.copyProperties(cart,orderDetail);
            //将订单id封装到orderDetail对象
            orderDetail.setOrderId(cart.getId());
            //将orderDetail对象添加到List集合中
            orderDetailList.add(orderDetail);
        }


        //将LIst集合中的对象批量插入订单明表中
        orderDetailMapper.insertBatch(orderDetailList);

        //清空当前微信登录用户的购物车数据
        shoppingCartMapper.deleteShoppingCartByUserId(wx_user_id);

        //将数据封装OrderSubmitVO 返回结果
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .id(orders.getId())
                .build();


        return orderSubmitVO;
    }

    /**
     * 订单支付
     * @param ordersPaymentDTO
     * @return
     */
    @Override
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) {
        //获取当前微信登录用户id
        Long wx_user_id = BaseContext.getCurrentId();
        //根据当前微信登录用户id获取到用户信息
        User user = userMapper.getByUserId(wx_user_id);

        //创建JSON对象
        JSONObject jsonObject = new JSONObject();
        //调用微信支付接口，生成微信支付交易单
        //jsonObject = wxChatPayUtil.pay(ordersPaymentDTO.getOrderNumber(),new BigDecimal(0.01),"中西药购销订单",user.getOpenid());

        if(jsonObject.getString("code") != null && jsonObject.getString("code ").equals("ORDERPAID")){
            throw new OrderBusinessException(MessageConstant.ORDER_REALLY_PAY);
        }

        jsonObject.put("code","ORDERPAID");
        OrderPaymentVO orderPaymentVO = jsonObject.toJavaObject(OrderPaymentVO.class);
        orderPaymentVO.setPackageStr(jsonObject.getString("package"));
        //支付状态，已支付
        Integer OrderPaidStatus = Orders.PAID;
        //订单状态，待接单
        Integer OrderStatus = Orders.TO_BE_CONFIRMED;
        //更新支付时间
        LocalDateTime payTime = LocalDateTime.now();
        orderMapper.updateStatus(OrderStatus,OrderPaidStatus,payTime,this.orders.getId());

        //通过websocket向客户浏览器推送消息 type orderId content
        Map map = new HashMap<>();
        //1 表示来单提醒  2  表示客户催单
        map.put("type",1);
        map.put("orderId",this.orders.getId());
        map.put("content","订单号："+this.orders.getNumber());

        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);

        return orderPaymentVO;
    }

    /**
     * 历史订单分页查询
     * @param page
     * @param pageSize
     * @param status
     * @return
     */
    @Override
    public PageResult ordersPageQuery(int page, int pageSize, Integer status){
        //获取当前微信登录用户id
        Long wx_user_id = BaseContext.getCurrentId();

        //设置分页
        PageHelper.startPage(page,pageSize);

        //创建OrdersPageOueryDTO对象
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();

        //将当前微信登录用户id封装到 ordersPageQueryDTO 中
        ordersPageQueryDTO.setUserId(wx_user_id);

        //封装 状态 到 ordersPageQueryDTO 中
        ordersPageQueryDTO.setStatus(status);

        //分页条件查询
        Page<Orders> historyOrderPage = orderDetailMapper.orderDetailPageQuery(ordersPageQueryDTO);

        //创建OrderVOList集合对象
        List<OrderVO> orderVOList = new ArrayList<>();

        //判断分页查询后 historyOrderPage 是否为空，不为空则有记录
        //查出订单明细，并封装到 orderVOList 集合中
        if(!CollectionUtils.isEmpty(historyOrderPage) && historyOrderPage.size() > 0){
            //遍历记录
            for(Orders historyOrder : historyOrderPage){
                //创建新的orderVO对象
                OrderVO orderVO = new OrderVO();
                //对象拷贝
                BeanUtils.copyProperties(historyOrder,orderVO);
                //获取到订单id
                Long orderByiId = historyOrder.getId();
                //根据订单id查询订单明细数据（集合）
                List<OrderDetail> orderDetailList = orderDetailMapper.geOrderDetailtByOrderId(orderByiId);
                //将订单明细数据通过orderDetails集合的形式封装到orderVO中的orderDetailList属性中
                orderVO.setOrderDetailList(orderDetailList);
                //将orderVO对象添加到orderVOList集合中
                orderVOList.add(orderVO);
            }
        }

        return new PageResult(historyOrderPage.getTotal(),orderVOList);

    }

    /**
     * 查询订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO selectOrderDetails(Long id) {
        //根据id查询订单
        Orders order1 = orderMapper.getOrderById(id);

        //获取到当前订单id
        Long orderById = order1.getId();

        //根据订单id查询订单明细
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orderById);

        //创建orderVO对象
        OrderVO orderVO = new OrderVO();

        //对象拷贝
        BeanUtils.copyProperties(order1,orderVO);

        //将订单明细封装到orderVO中
        orderVO.setOrderDetailList(orderDetailList);

        return orderVO;
    }

    /**
     * 取消订单
     * @param id
     */
    @Override
    public void cancelOrder(Long id)  throws Exception{
        //根据id查询订单信息
        Orders orderById = orderMapper.getOrderById(id);

        //查询出来的订单是否存在，不存在抛出业务异常
        if(ObjectUtil.isNotEmpty(orderById)){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //订单状态 1 待付款  2 待接单  3 已接单  4 派送中  5 已完成  6 ；已取消
        //如果订单已接单、派送中、已完成、已取消   不能取消订单
        if(orderById.getStatus() > TO_BE_CONFIRMED){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //创建orders对象
        Orders orders = new Orders();

        //将查询出来的 订单id 封装到 orders 对象
        Long id1 = orderById.getId();
        orders.setId(id1);

        //订单处于待接单状态下取消，需要进行退款
        if(orderById.getStatus().equals(Orders.TO_BE_CONFIRMED)){
            //调用微信退款接口
            //商家订单号 用户退款单号  退款金额 单元 元   原来订单金额
            //weChatPayUtil.refund(orderById.getNumber(),orderById.getNumber(),new BigDecimal(0.01),new BigDecimal(0.01));

            //支付状态修改为退款
            orders.setPayStatus(Orders.REFUND);
        }

        //更新订单状态、取消原因、取消时间
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelTime(LocalDateTime.now());
        orders.setCancelReason(USER_CANCEL);
        orderMapper.update(orders);
    }

    /**
     * 再来一单
     * @param id
     */
    @Override
    public void repetition(Long id) {
        //获取当前登录用户id
        Long wx_user_id = BaseContext.getCurrentId();
        //根据订单id查询订单详情信息
        List<OrderDetail> OrderDeailByOrderIdList = orderDetailMapper.getByOrderId(id);

        //将订单转化为购物车对象
        List<ShoppingCart> shoppingCartList = OrderDeailByOrderIdList.stream().map(shopCart -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(shopCart,shoppingCart,"id");
            shoppingCart.setUserId(wx_user_id);
            shoppingCart.setCreateTime(LocalDateTime.now());
            return shoppingCart;
        }).collect(Collectors.toList());

        //将购物车对象批量添加到数据库
        shoppingCartMapper.insertBatch(shoppingCartList);
    }

    /**
     * 客户催单
     * @param id
     */
    @Override
    public void remider(Long id) {
        //根据订单id查询订单
        Orders orderById = orderMapper.getOrderById(id);

        //判断查询出来的订单是否存在，存在且订单状态不为4 抛出业务异常
        if(ObjectUtil.isNotEmpty(orderById) && orderById.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Map map = new HashMap();
        //type类型为2表示客户催单
        map.put("type",2);
        map.put("orderId",id);
        map.put("content","订单号："+orderById.getNumber());

        //通过websocket向客户端浏览器推送消息
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

    /**
     * 支付成功，修改订单状态
     * @param outTradeNo
     */
    @Override
    public void paySuccess(String outTradeNo) {
        //根据订单号查询订单信息
        Orders ordersDB = orderMapper.getByoutTradeNo(outTradeNo);

        Long ordersDBId = ordersDB.getId();
        Integer toBeConfirmed = Orders.TO_BE_CONFIRMED;
        Integer pay_status = Orders.PAID;

        //根据订单id更新订单状态、字符方式、支付状态、结账时间
        Orders paySuccess_order = new Orders();
        paySuccess_order.setId(ordersDBId);
        paySuccess_order.setStatus(toBeConfirmed);
        paySuccess_order.setPayStatus(pay_status);
        paySuccess_order.setCheckoutTime(LocalDateTime.now());

        //通过websocket向客户浏览器推送消息 type orderId content
        Map<String,Object> map = new HashMap<>();
        //type类型为2表示客户支付了
        map.put("type",1);
        map.put("orderId",ordersDBId);
        map.put("content","订单号："+outTradeNo);

        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);

    }

    @Override
    public void alipayPay(HttpServletRequest httpRequest, HttpServletResponse httpResponse) {

    }

    @Override
    public boolean getAlipayPayDetails() {
        return false;
    }


}
